@inject NavigationManager NavigationManager
@inject TokenProvider TokenProvider
@inject IJSRuntime JSRuntime
@inject ProtectedLocalStorage ProtectedLocalStorage

@using Microsoft.AspNetCore.Components.Server.ProtectedBrowserStorage
@using ClassifiedAds.BlazorServerSide.Shared

<CascadingAuthenticationState>
    <Router AppAssembly="@typeof(Program).Assembly" AdditionalAssemblies="new[] { typeof(ClassifiedAds.Blazor.Modules.Core.Components.ConfirmDialog).Assembly}">
        <Found Context="routeData">
            <AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)">
                <NotAuthorized>
                    Please <a href="/login?returnUrl=@("/"+NavigationManager.ToBaseRelativePath(NavigationManager.Uri))">Login</a>
                </NotAuthorized>
            </AuthorizeRouteView>
        </Found>
        <NotFound>
            <LayoutView Layout="@typeof(MainLayout)">
                <p>Sorry, there's nothing at this address.</p>
            </LayoutView>
        </NotFound>
    </Router>
</CascadingAuthenticationState>

@code{
    [Parameter]
    public TokenProvider InitialState { get; set; }

    protected async override void OnInitialized()
    {
        var tokens = (await ProtectedLocalStorage.GetAsync<TokenProvider>("tokens")).Value;

        if (InitialState != null)
        {
            if (tokens == null || tokens.ExpiresAt < InitialState.ExpiresAt)
            {
                tokens = InitialState;
                await ProtectedLocalStorage.SetAsync("tokens", tokens);
            }

            TokenProvider.AccessToken = tokens.AccessToken;
            TokenProvider.RefreshToken = tokens.RefreshToken;
            TokenProvider.ExpiresAt = tokens.ExpiresAt;

            if (TokenProvider.TokenExpired)
            {
                // TODO: relogin
                //JSRuntime.Alert($"/login?returnUrl=/{ NavigationManager.ToBaseRelativePath(NavigationManager.Uri)}");
            }

            TokenProvider.IsReady = true;
        }

        base.OnInitialized();
    }
}
